package setting

import (
	wechat_model "code.gitea.io/gitea/models/wechat"
	"code.gitea.io/gitea/modules/log"
	context "code.gitea.io/gitea/services/context"
	wechat_service "code.gitea.io/gitea/services/wechat"
)

// BindWechatQR 将二维码扫描人 OpenID 关联到数据库用户中
func BindWechatQR(ctx *context.Context) {

	// 1. 取出 微信公众号二维码 ticket
	ticket := ctx.Base.Req.URL.Query().Get("ticket")

	// 2. 取出用户openid并清空对应的ticket
	qrStatus, err := wechat_service.GetWechatQrStatusByTicket(ticket)
	if err != nil {
		log.Error("绑定微信失败: " + err.Error())
		ctx.Flash.Error("绑定微信失败：" + err.Error())
		ctx.Redirect("/user/settings/account")
		return
	}
	defer wechat_service.DeleteWechatQrByTicket(ticket)

	// 3. 从 Gitea Web Context 中获取用户信息
	user := ctx.Doer

	// 4. 更新数据库 `user_wechat_openid`
	err = wechat_model.UpdateOrCreateWechatUser(ctx, user, qrStatus.OpenId)
	if err != nil {
		log.Error("绑定微信失败: " + err.Error())
		ctx.Flash.Error("绑定微信失败: " + err.Error())
		ctx.Redirect("/user/settings/account")
		return
	}

	// 5. 携带扫码成功信息，重定向回用户修改信息页面
	ctx.Data["wechatQRScanSuccess"] = true
	Account(ctx)
}

// UnbindWechatQR 解绑微信
func UnbindWechatQR(ctx *context.Context) {
	_ = wechat_model.DeleteWechatUser(ctx, ctx.Doer)
	ctx.Flash.Success(ctx.Tr("settings.wechat_unbind_success"))
	ctx.Redirect("/user/settings/account")
}
